package jwt

import (
	"errors"
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"time"
)

type JwtHelper struct {
	PrivateKey string
	alt        jwt.SigningMethod
}

var (
	DEFAULT_PRV_KEY            = "default_secret"
	DEFAULT         *JwtHelper = NewJwtHelper(DEFAULT_PRV_KEY)
)

func Default() *JwtHelper {
	return DEFAULT
}

func NewJwtHelper(privateKey string) *JwtHelper {
	return &JwtHelper{PrivateKey: privateKey, alt: jwt.SigningMethodHS256}
}

func (h *JwtHelper) Sign(claims jwt.Claims, timeout time.Duration) (string, error) {
	cm, ok := claims.(jwt.MapClaims)
	if !ok {
		return "", errors.New("claims is not jwt.MapClaims")
	}
	_, ok = cm["exp"]
	if !ok {
		cm["exp"] = time.Now().Add(timeout).Unix()
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	ts, err := token.SignedString([]byte(h.PrivateKey))
	if err != nil {
		fmt.Println(err)
		return "", err
	}
	return ts, nil
}

func (h *JwtHelper) Verify(jwttoken string) (jwt.Claims, error) {
	token, err := jwt.Parse(jwttoken, func(*jwt.Token) (interface{}, error) {
		return []byte(h.PrivateKey), nil
	})

	return token.Claims, err
}
